import React, { ReactNode } from 'react'
import { Button, Modal, message, Input, Select, TreeSelect, Upload, Spin, Affix, BackTop } from 'antd'
import { BaseListPage, IBaseListPageProps, IBaseListPageState, UdSelectAjax, uaaApp, validators, BasePage, UdPage, UdPageHeader, udConfigProvider, IUdFormItem, UdFilter, UdToolbar, UdTable, IUdColumn, IUdTableProps } from '../../../lib'
import { columnRenders } from '../../../lib/utils/columnRenders'
import { UdModal, UdModalForm } from '../../../lib/ui/UdModal'
import { http } from '../../../lib/core/http'
import apis from "@/apis/UserManagement";
import { resetPassword, enableHandle } from '../common'
import _ from 'lodash'
import EnableRadioGroup from '../component/EnableRadioGroup'
import comApis from '@/apis'
import './style.scss'
import { downBlobFile } from '@/utils/methods'
import { RouteComponentProps } from 'react-router-dom'
import { WrappedFormUtils } from 'antd/lib/form/Form'
import OrgTree from './component/OrgTree'
import ButtonGroup from 'antd/lib/button/button-group'
import { PaginationConfig } from 'antd/lib/table'

const confirm = Modal.confirm
const Option = Select.Option

const EnableBtnAuth = 'user_lzlj_employee_manager_invalid'
const UpdateBtnAuth = 'user_lzlj_employee_manager_add'
const ResetPasswordBtnAuth = 'user_lzlj_employee_manager_rest_password'

class InternalStaffList extends BaseListPage<IInternalStaffListProps, IInternalStaffListState> {

  protected saveParamsWithUrl: boolean = true

  private statusTranslate = {
    0: '禁用',
    1: '启用',
  }

  private statusOptions = [...Object.keys(this.statusTranslate).map(key=>({value: key, name: this.statusTranslate[key]}))]

  private modal

  constructor(props: IInternalStaffListProps) {
    super(props)

    this.state = {
      title: '内部员工账号管理',
      queryApi: apis.InternalStaffList,
      conditions: [
        { id: 'userCode', label: '员工编码' },
        { id: 'realName', label: '员工姓名' },
        // { id: 'roleName', label: '角色' },
        { id: 'isValid', label: '状态', render: 
          <Select placeholder='请输入状态'>
            {this.statusOptions.map(({value, name})=><Option key={value} value={value}>{name}</Option>)}
          </Select>
        },
      ],
      rowKey: 'id',
      columns: [
        ['员工编码', 'userCode', null, { minWidth: '80px' }],
        ['员工姓名', 'realName', null, { minWidth: '70px' }],
        ['员工手机号', 'phone', null, { minWidth: '80px' } ],
        ['所属组织', 'mechanismName', null, { width: '20%',minWidth: '220px' } ],
        ['角色', 'roleName', null, { width: '20%',minWidth: '100px' }],
        ['状态', 'isValid', columnRenders.enum(this.statusTranslate), { minWidth: '40px' }],
        ['创建时间', 'createTime', null, { minWidth: '100px' } ],
        ['最近修改时间', 'updateTime', null, { minWidth: '100px' } ],
        ['最近修改人', 'updateBy', null, { minWidth: '70px' } ],
        {
          title: '操作',
          dataIndex: 'operate',
          fixedWidth: '100px',
          allowCustomize: false,
          fixed: 'right',
          render: columnRenders.operate([
            {
              title: '编辑', auth: UpdateBtnAuth, action: (text: any, row: any) => this.edit(row)
            },
            {
              title: '重置密码', auth: ResetPasswordBtnAuth, action: (text: any, record: any) => {
                confirm({
                  title: '确定要重置登录密码吗？',
                  onOk: () => {
                    this.resetPassword(record)
                  }
                })
              }
            },
          ])
        }
      ],
      leftBtns: [
        <Button type='primary' onClick={this.addUser}>新增</Button>,
        <Button type='primary' onClick={this.importModal}>导入</Button>,
        uaaApp.canUse(EnableBtnAuth)&&(()=><Button type="primary" disabled={!this.existSelectedRow()} onClick={()=>this.enableHandle(true)}>启用</Button>),
        uaaApp.canUse(EnableBtnAuth)&&(()=><Button disabled={!this.existSelectedRow()} onClick={()=>this.enableHandle(false)}>禁用</Button>),
      ],
      tableProps: {
        rowSelection: !uaaApp.canUse(EnableBtnAuth) ? null : {},
        scroll: {
          x: true,
        }
      },
      organizationList: [],
      roleList: [],
      uploading: false,
    }
  }

  public componentWillMount() {
    super.componentWillMount()
    this.getOrganizationList()
    this.getRoleSelectList()
  }

  render() {
    return (
      <Spin spinning={this.state.uploading} tip='正在上传，请稍后...'>
        {super.render()}
      </Spin>
    )
  }

  private getOrganizationList = () => {
    http.get(comApis.OrganizationTreeByUser).then(res=>{
      const { nodes } = this.frormatTreeData([res.data])
      this.setState({
        organizationList: nodes,
      })
    })
  }

  private getRoleSelectList = () => {
    const params = {roleType:0}
    http.get(apis.RoleSelectList,{params}).then(res=>{
      const roleList = res.data.map(({id,name})=>({value:id,name}))
      this.setState({
        roleList,
      })
    })
  }

  private frormatTreeData = (datas) => {
    let nodes: any = []
    const loopFormat = (datas) => {
      if (!_.isArray(datas) || datas.length == 0) {
        return []
      }
      let treeNodes = []
      datas.map(item=>{
        const { children, name: title, id: key, id: value } = item
        let treeNode = { key, value, title, children }
        treeNode.children = loopFormat(children)
        treeNodes.push(treeNode)
      })
      return treeNodes
    }
    nodes = loopFormat(datas)
    return { nodes }
  }

  private importModal = () => {
    this.modal = UdModal.open({
      title: '导入员工',
      width: 300,
      content: <>
        <div className='import-user-modal'>
          <Button type='primary' onClick={this.downloadTpl}>下载模板</Button>
          <Upload showUploadList={false} customRequest={this.importUser}><Button type='primary'>导入员工</Button></Upload>
        </div>
      </>,
      footer: null,
      maskClosable: false,
      centered: true,
    })
  }

  private importUser = (option) => {
    this.modal && this.modal.destroy()
    this.setState({uploading: true})
    const { file } = option
    const formData = new FormData()
    formData.append('file', file)
    http.post(apis.ImportInternalStaff, formData).then(res => {
      message.success('上传成功')
      this.query()
    }).finally(() => this.setState({uploading: false}))
  }

  private downloadTpl = () => {
    http.get(apis.DownloadInternalStaffTpl, { responseType: 'arraybuffer' }).then(res => {
      if (!res.data.code) {
        downBlobFile(res.data, '内部员工导入模板')
      }
    })
  }

  private addUser = () => {
    const initValue = {
      isValid: 1,
    }
    const { organizationList,roleList } = this.state
    UdModal.open({
      title: '新增',
      content: <UdModalForm items={[
        { id: 'userCode', label: '员工编码', rules: [validators.required, validators.max(10), validators.userCode] },
        { id: 'realName', label: '员工姓名', rules: [validators.required, validators.max(10), validators.userName] },
        { id: 'phone', label: '员工手机号', rules: [validators.required, validators.phoneCommonly], decoratorOptions: { validateFirst: true } },
        { id: 'orgCode', label: '所属组织', render: 
          <TreeSelect treeNodeFilterProp="title" multiple={false} getPopupContainer={triggerNode=>triggerNode.parentElement} showSearch={true} treeData={organizationList} />
        },
        { id: 'roleId', label: '角色', render: ()=>(
          <Select getPopupContainer={triggerNode=>triggerNode.parentElement} mode="multiple" optionFilterProp="children">
            {roleList.map(({value, name})=><Option key={value} value={value}>{name}</Option>)}
          </Select>
        )},
        { id: 'isValid', label: '状态', render: <RadioCm /> },
      ]} values={initValue} />,
      onOk: (values) => {
        console.log(values)
        return http.post(apis.AddInternalStaff, values).then(res=>{
          message.success('新增成功')
          this.query()
        })
      }
    })
  }

  private edit = (row) => {
    const {organizationList,roleList} = this.state
    if (!Array.isArray(row.roleId)) {
      row.roleId = row.roleId?.split(',')
    }
    UdModal.open({
      title: '编辑',
      content: <UdModalForm items={[
        { id: 'userCode', label: '员工编码', render: <Input disabled /> },
        { id: 'realName', label: '员工姓名', render: <Input disabled /> },
        { id: 'phone', label: '员工手机号', render: <Input disabled /> },
        /* { id: 'depmentId', label: '所属组织', render: 
          <Select>
            <Option value='1'>泸州老窖</Option>
          </Select>
        }, */
        { id: 'depmentId', label: '所属组织', render: 
          <TreeSelect treeNodeFilterProp="title" multiple={false} getPopupContainer={triggerNode=>triggerNode.parentElement} showSearch={true} treeData={organizationList} />
        },
        { id: 'roleId', label: '角色', render: ()=>(
          <Select getPopupContainer={triggerNode=>triggerNode.parentElement} mode="multiple" optionFilterProp="children">
            {roleList.map(({value, name})=><Option key={value} value={value}>{name}</Option>)}
          </Select>
        )},
        { id: 'isValid', label: '状态', render: <RadioCm /> },
      ]} values={row} />,
      onOk: (values) => {
        values.id = row.id
        // 修改需要给旧的组织id
        values.oldDepmentId = row.depmentId
        console.log(values)
        return http.post(apis.UpdateInternalStaff, values).then(res=>{
          message.success('编辑成功')
          this.query()
        })
      }
    })
  }

  private resetPassword = (row) => {
    const { id } = row;
    return resetPassword({
      url: apis.ResetPasswordInternalStaff,
      params: {id},
    })
  }

  private enableHandle = (flag) => {
    const idList = this.state.selectedRowKeys?.join(',')
    const isValid = flag?1:0
    enableHandle({
      flag,
      url: apis.EnableInternalStaff,
      params: {
        idList,
        isValid,
      },
      cb: ()=>{
        this.query()
      }
    })
  }

  /* private enableHandle(flag) {
    const type = flag?"启用":"禁用"
    confirm({
      title: '确定要'+type+'所选账号吗？',
      onOk: () => {
        return this.enableRequest(flag)
      }
    })
  }

  private enableRequest = (flag) => {
    const ids = this.state.selectedRowKeys
    return http.post("/resetPassword",{ids}).then(res=>{
      const msg = flag?"启用成功":"禁用成功"
      message.success(msg)
      this.query()
    })
  } */

}

function RadioCm(props) {
  return (
    <EnableRadioGroup onChange={props.onChange} value={props.value} />
  )
}

interface IInternalStaffListProps extends IBaseListPageProps {

}

interface IInternalStaffListState extends IBaseListPageState {
  organizationList: any
  roleList: any
  uploading?: boolean
}

